#include "main.hpp"

#define PORT  8080
#define LOCAL_PORT 40221
char* server_ip = (char*)"192.168.1.201";
char* local_ip = (char*)"192.168.1.202";

struct sockaddr_in seraddr;
struct sockaddr_in localaddr;
socklen_t add_len;
//设置UDP为非堵塞模式
static void setnonblocking(int sockfd) {
    int flag = fcntl(sockfd, F_GETFL, 0);
    if (flag < 0) {
        printf("堵塞设置错误\n");
        return;
    }
    if (fcntl(sockfd, F_SETFL, flag | O_NONBLOCK) < 0) {
        printf("堵塞设置错误222\n");
    }
}

//初始化UDP端口号以及IP
int UDP_init()
{
    int fd = socket(AF_INET, SOCK_DGRAM, 0);

    setnonblocking(fd);

    add_len = sizeof(seraddr);

    memset(&seraddr, 0, add_len);
    memset(&localaddr, 0, add_len);

    seraddr.sin_family = AF_INET;
    seraddr.sin_port = htons(PORT);
    seraddr.sin_addr.s_addr = inet_addr(server_ip);

    localaddr.sin_family = AF_INET;
    localaddr.sin_port = htons(LOCAL_PORT);
    localaddr.sin_addr.s_addr = inet_addr(local_ip);


    while (bind(fd, (struct sockaddr *)&localaddr, add_len) == -1) {
        printf("bind udp error!\n");
    }

    if(fd < 0)
    {
        printf("UDP init  failed,%s\n",strerror(errno));
        return -1;
    }
    else{
        printf("UDP init successfully\n");
        return fd;
    }
}

//UDP 发送数据
//sendbuf：需要发送的数据数组
//fd     ：对应的UDP服务端
int UDP_send(uint8_t* sendbuf,int fd,uint8_t length)
{
    int ret;

    sendto(fd, sendbuf, length, 0, (struct sockaddr *)&seraddr, add_len);
    for(int i=0;i<length;++i)
    {
       // printf("send data[%d] = %x\n",i,sendbuf[i]);
    }
    memset(sendbuf,0,sizeof(sendbuf));
    return 0;
}


//UDP 接收数据，若读到数据则返回数据长度；若没有数据，返回-1；默认返回0
//recvbuf：负责接收数据的数组
//fd     ：对应的UDP服务端
int UDP_recv(uint8_t* recvbuf,int fd)
{

    int ret = recvfrom(fd,recvbuf,256,0,(struct sockaddr *)&seraddr, &add_len);

    if(ret == -1)
    {
        // printf("没有读到数据\n");
        return 0;
    }
    else{
            // for(uint8_t i =0;i<ret;i++)
            // {
            //     printf("ret = %d\n",ret);
            //     printf("recvbuf[%d] = %x\n",i,recvbuf[i]);
            // }
        return ret;
    }
}

//关闭UDP端口
int UDP_close(int fd)
{
    close(fd);
    return 0;
}


//将UDP端口读到数据存入相应的环形缓冲区
void UDP_read_raw_data(int fd,circleBuf_t* temp)
{
    uint8_t radio_read_buf[256];
    uint8_t cnt = UDP_recv(radio_read_buf,fd);
    uint16_t head_n = 0;
    if(cnt != 0)
    {
        for(uint8_t i=0; i<cnt; ++i){
            //! 取得下一个环形缓冲区的头指针
            //! 并判断是否头指针追上了尾指针
            head_n = (temp->head+1)%CIRCLE_BUF_SIZE;
            if(head_n != temp->tail){
                temp->buf[temp->head] = radio_read_buf[i];
                temp->head = head_n;
                // printf("radio_read_buf[%d] = %x\n",i,radio_read_buf[i]);

            }
        }
    }
}
